package 聊天室练习.聊天室练习01;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client2 {
    private Socket socket = null;
    private ExecutorService threadPool = Executors.newFixedThreadPool(2);

    public Client2(){
        System.out.println("正在连接服务器");

        try {
            socket = new Socket("localhost",8088);
        } catch (IOException e) {
            System.out.println("连接失败");
            return;
        }

        System.out.println("连接服务器成功");
    }

    private void start(){
        if (socket != null){
            try(
                    OutputStream os = socket.getOutputStream();
//                OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-8");
                    PrintWriter pw = new PrintWriter(os,true);
            ) {

                ServerHandler serverHandler = new ServerHandler();
//                Thread t = new Thread(serverHandler);
//                t.start();
                threadPool.execute(serverHandler);


                Scanner scanner = new Scanner(System.in);
                while (true){
                    System.out.println("请输入要发送的消息：");
                    String line = scanner.nextLine();
                    pw.println(line);
                }


            } catch (IOException e) {
                System.out.println("与服务器断开了");
            }
        }





    }

    private void acceptMessage(){
        try(
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,"UTF-8");
                BufferedReader br = new BufferedReader(isr);
        ) {
            String line;
            while ((line = br.readLine()) != null){
                System.out.println(line);
            }


        } catch (IOException e) {
            System.out.println("与服务器断开了");
        }
    }

    private class ServerHandler implements Runnable{


        public void run(){
            acceptMessage();
        }
    }

    public static void main(String[] args) {
        Client2 client = new Client2();
        client.start();
    }
}
